package com.example.mgs.config;


import com.example.common.constants.ActivityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class ActivityRabbitMQConfig {

    // 用户活跃度交换机
    public static final String USER_ACTIVITY_EXCHANGE = ActivityConstants.USER_ACTIVITY_EXCHANGE;

    // 教师活跃度队列
    public static final String TEACHER_ACTIVITY_QUEUE = ActivityConstants.TEACHER_ACTIVITY_QUEUE;

    // 学生活跃度队列
    public static final String STUDENT_ACTIVITY_QUEUE = ActivityConstants.STUDENT_ACTIVITY_QUEUE;

    // 死信交换机
    public static final String DLX_EXCHANGE = ActivityConstants.DLX_EXCHANGE;

    // 死信队列
    public static final String DLX_QUEUE = ActivityConstants.DLX_QUEUE;

    // 创建用户活跃度交换机
    @Bean
    DirectExchange userActivityExchange() {
        log.info("创建用户活跃度交换机");
        return new DirectExchange(USER_ACTIVITY_EXCHANGE);
    }

    // 创建死信交换机
    @Bean
    DirectExchange dlxExchange() {
        log.info("创建死信交换机");
        return new DirectExchange(DLX_EXCHANGE);
    }

    // 创建教师活跃度队列，并绑定死信交换机
    @Bean
    Queue teacherActivityQueue() {
        log.info("创建教师活跃度队列");
        return QueueBuilder.durable(TEACHER_ACTIVITY_QUEUE)
                .withArgument(ActivityConstants.X_DEAD_LETTER_EXCHANGE, DLX_EXCHANGE)
                .withArgument(ActivityConstants.X_DEAD_LETTER_ROUTING_KEY, ActivityConstants.DLX_ROUTING_KEY)
                .build();
    }

    // 创建学生活跃度队列，并绑定死信交换机
    @Bean
    Queue studentActivityQueue() {
        log.info("创建学生活跃度队列");
        return QueueBuilder.durable(STUDENT_ACTIVITY_QUEUE)
                .withArgument(ActivityConstants.X_DEAD_LETTER_EXCHANGE, DLX_EXCHANGE)
                .withArgument(ActivityConstants.X_DEAD_LETTER_ROUTING_KEY, ActivityConstants.DLX_ROUTING_KEY)
                .build();
    }

    // 创建死信队列
    @Bean
    Queue dlxQueue() {
        return new Queue(DLX_QUEUE, true);
    }

    // 绑定教师队列到交换机
    @Bean
    Binding bindingTeacherQueue() {
        return BindingBuilder.bind(teacherActivityQueue())
                .to(userActivityExchange())
                .with(ActivityConstants.TEACHER_ROUTING_KEY);
    }

    // 绑定学生队列到交换机
    @Bean
    Binding bindingStudentQueue() {
        return BindingBuilder.bind(studentActivityQueue())
                .to(userActivityExchange())
                .with(ActivityConstants.STUDENT_ROUTING_KEY);
    }

    // 绑定死信队列到死信交换机
    @Bean
    Binding bindingDlxQueue() {
        return BindingBuilder.bind(dlxQueue())
                .to(dlxExchange())
                .with(ActivityConstants.DLX_ROUTING_KEY);
    }
}
